<?php
/**
 * UploadFilesInfoAction class file.
 *
 * @package   controllers
 * @subpackage patientSignal
 * @since     1.0
 * @filesource
 */

Yii::import('application.controllers.patientSignal.AbstractUploadAction');

/**
 * Actin class to save signal files update information to server.
 * This action class will be integrated by PatientSignalController.
 * @see PatientSignalController 
 */
class UpdateFilesSaveAction extends AbstractUploadAction {

	/**
	 * Ajax callback method to pass the orginal file name to the server and returns current session files for user selection.
	 * @throws if user has no update access to the patient signal.
	 * @throws if the signal is not editable.
	 */
	public function run($signalId){
		$patientSignal=$this->getController()->loadModel($signalId);

		//check if the user has right to download a file.
		if(!Yii::app()->user->checkAccess('signalUpdate',array('organizationId'=>$patientSignal->organizationId))){
			throw new CHttpException(403,'You do not have permission to update this record.');
		}
		if(!$patientSignal->isEditable()){
			throw new CHttpException(403,'This signal cannot be updated.');
		}

		// if upload file name is not valid, return error information. Stop fllowing processing.
		if(!$this->isLegalFileName($_POST['name'])){
			echo CJSON::encode(array(
				'success'=>false,
				'message'=>'The file '.$_POST['name']. ' contains non-ascii character. Please use ascii character: a-z A-Z 0-9, these special chars: dot .  brackets: ( ) [ ] dash: - underscore: _ only.',
			));
			$this->removeSessionFile($_POST['id']);
			return;
		}
		
		// if upload file alreay is uploaded, return error infomration. Stop fllowing processing.
		if($this->filenameExist($patientSignal,$_POST['name'])){
			echo CJSON::encode(array(
				'success'=>false,
				'message'=>'The file '.$_POST['name']. ' exist in current upload. Please choose a file with different name.',
			));
			$this->removeSessionFile($_POST['id']);
			return;
		}
		
		// Save upload file on server. return the file name and delete link on page if successful, otherwise return error message.
		$sessionFileInfo=$this->getSessionFileInfo();
		$fileInfo=$sessionFileInfo[$_POST['id']];
		$patientSignalFile=new PatientSignalFile();
		$patientSignalFile->patientSignalId=$signalId;
		$fileName=$this->createSignalFilename($patientSignal,$_POST['name']);
		$patientSignalFile->filename=$fileName;
		$moveFileSuccess=rename($fileInfo['path'], $patientSignal->signalPath.DIRECTORY_SEPARATOR.$fileName);
		if($moveFileSuccess && $patientSignalFile->save()){				
			echo CJSON::encode(array(
				'success'=>true,
				'fileId'=>$patientSignalFile->id, 
				'filename'=>$fileName,
				'deleteUrl'=>$this->getController()->createUrl('patientSignal/deleteSignalFile',array('fileId'=>$patientSignalFile->id)),
			));
		}else{
			echo CJSON::encode(array(
				'success'=>false,
				'message'=>'Error processing file '.$_POST['name'],
			));
		}
		$this->removeSessionFile($_POST['id']);	
	}

	/**
	 * Check if the filename already exists in given patient signal.
	 * @param PatientSignal $patientSignal
	 * @param string $filename
	 * @return boolean true | false if exists or not.
	 */
	private function filenameExist($patientSignal,$filename) {
		$signalFiles=$patientSignal->signalFiles;
		$filename=$this->createSignalFilename($patientSignal, $filename);
		foreach ($signalFiles as $signalFile){
			if($signalFile->filename==$filename){
				return true;
			}
		}
		return false;
	}
}